package cn.grf.datasource.service;

import cn.grf.datasource.pojo.User;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author grf
 * @apiNote
 * @since 2025/4/23
 */
@Service
@RequiredArgsConstructor
@Transactional(transactionManager = "primaryTransactionManager")
public class UserService {

    @Qualifier("primaryJdbcTemplate")
    private final JdbcTemplate primaryJdbcTemplate;


    public void insert(User user) {
        var sql = """
            INSERT INTO user (id, username, password, sex, age) VALUES (?, ?, ?, ?, ?)
        """;
        primaryJdbcTemplate.update(sql, user.getId(), user.getUsername(), user.getPassword(), user.getSex(), user.getAge());
    }

    public List<User> list() {
        String sql = "SELECT * FROM user";
        return primaryJdbcTemplate.queryForList(sql, User.class);
    }

    public User get(Long id) {
        String sql = "SELECT * FROM user where id = ?";
        return primaryJdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
    }
}
